package root.action;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;
import root.service.LoginService;
import root.utils.DesUtils;
import root.utils.StringHelper;
import root.utils.WebConstants;

import javax.servlet.http.Cookie;

/**
 * 用户登录
 * @author 吕梁山
 * @date 2018/9/26
 */
public class LoginAction extends Controller {

    private LoginService loginService = new LoginService();

    public void index() throws Exception {
        String username = getPara("username");
        String password = getPara("password");
        int rememberMe = getParaToInt("rememberMe",0);
        JSONObject object = new JSONObject();
        if (StringHelper.isEmpty(username) || StringHelper.isEmpty(password)) {
            object.put("code", 1);
            object.put("error", "请输入账号密码");
            renderJson(object);
            return;
        }
        Record row = loginService.getLoginUser(username);
        if (row == null) {
            object.put("code", 1);
            object.put("error", "帐号或密码错误");
            renderJson(object);
            return;
        }
        DesUtils desUtils = new DesUtils();
        password = desUtils.encrypt(password + WebConstants.PASS_KEY);

        if (!row.get("password").equals(password)) {
            object.put("code", 1);
            object.put("error", "帐号或密码错误");
            renderJson(object);
            return;
        }
        String encrypt = desUtils.encrypt(username + "_" + password);
        Cookie cookie = new Cookie(WebConstants.MANAGER_USER,encrypt);
        cookie.setPath("/");
        if(rememberMe > 0){
            cookie.setMaxAge(3600*24*30);
        } else{
            cookie.setMaxAge(3600);
        }
        setCookie(cookie);
        loginService.updateUserLoginDate(row.getStr("id"));
        object.put("code", 0);
        renderJson(object);
    }

    /**
     * 退出登录
     */
    public void logOut (){
        JSONObject jsonObject = new JSONObject();
        Cookie cookie = new Cookie(WebConstants.MANAGER_USER,"1");
        cookie.setMaxAge(1);
        cookie.setPath("/");
        setCookie(cookie);
        jsonObject.put("code", 0);
        renderJson(jsonObject);
    }
}
